package com.ailk.keel.core.database.common;

import java.io.UnsupportedEncodingException;

/**
 * 需要在JVM参数中配置类似的参数：-Ddb.charset=iso-8859-1.GBK
 * @author xuhh
 *
 */
public class CharsetTansfer {
	
	private static String databaseCharsetName = System.getProperty("db.charset");
	private static String dbTransCharset = null;
	private static String dbInnerCharset = null;
	static{
		if(databaseCharsetName!=null)
		{
			String[] array = databaseCharsetName.split("\\.");
			if(array.length==2)
			{
				dbTransCharset = array[0];
				dbInnerCharset = array[1];   
			}
		}
	}
	
	/**
	 * 转换数据库字符集到Unicode
	 * @param dbstr
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String transform(String dbstr) throws UnsupportedEncodingException
	{
		if(dbstr==null) return null;
		if(dbTransCharset!=null && dbInnerCharset!=null)
		{
			byte[] byteArray = dbstr.getBytes(dbTransCharset);
			return new String(byteArray,dbInnerCharset);
		}
		else
		{
			return dbstr;
		}
	}
	
	/**
	 * 转换Unicode到数据库字符集
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String transform2db(String str) throws UnsupportedEncodingException
	{
		if(str==null) return null;
		if(dbTransCharset!=null && dbInnerCharset!=null)
		{
			byte[] byteArray = str.getBytes(dbInnerCharset);
			return new String(byteArray,dbTransCharset);
		}
		else
		{
			return str;
		}
	}
	
}
